<template>
	<view class="containerbox bgc-white">
		<uv-navbar :title="detail.course?.name" auto-back placeholder />
		<view class="py-20 px-30 border-bottom">
			<view class="text-28"><text class="text-gray mr-10">关卡{{detail.sort}}:</text>{{detail.title}}</view>
			<view class="flex items-center text-28 mt-20">
				<view>参考时长 {{detail.duration}}''</view>
				<view class="flex items-center ml-20">
					<view class="mr-15">难度系数</view>
					<view class="">
						<uni-icons type="star-filled" v-for="item,index in 5" :color="((detail.difficultyRate) <  item) ? '#bababa' : '#f69b2c'"></uni-icons>
					</view>
				</view>
			</view>
			<view class="text-24 text-qgray mt-10 flex items-center"><uni-icons type="info-filled" size="16" color="#a6a5a7"></uni-icons> 长按可加入生词表</view>
		</view>
		<scroll-view scroll-y class="containerbox relative px-30 pt-20">
			<c_reac_text :text="detail.content" :articleId="detail.id" ref="reactextRef" @callback="joinSucces"/>
		</scroll-view>
		<view class="flex items-center justify-between bottombox">
			<!-- <view class="flex-1 text-26" @click="selectListEvent" v-if="!isselect">查看关卡</view> -->
			<view class="btn bgc-warning" @click="playEvent">
				{{isplayStatus ? '取消' : '点读' }}
				<view class="mp3icon" v-if="isplayStatus">
					<view class="item"></view>
					<view class="item"></view>
					<view class="item"></view>
					<view class="item"></view>
				</view>
			</view>
			<view class="btn" :class="{'bgc-warning': !reactextStatus, 'bgc-primary': reactextStatus}" @click="switchStatus">{{!reactextStatus ? '生词' : '隐藏'}}</view>
			<view class="btn bgc-primary" @click="goMark" >
				识记<template v-if="wordlist.length">({{wordlist.length}})</template>
			</view>
			<view class="btn bgc-primary" @click="handleStart">{{isselect ? '查看解析' : '做题'}}</view>
		</view>
		
		<audio />
	</view>
	<uni-popup ref="popupRef" type="bottom" @change="popupStatusEvent" borderRadius="10px 10px 10px 10px" backgroundColor="#fff">
		<view class="bgc-white">
			<view class="text-32 text-center py-20">关卡列表</view>
			<scroll-view scroll-y style="max-height: 800rpx;">
				<c_ranklist v-if="isListShow" :examId="submitData.exerciseId" isGop @handle="handleRank" :courseId="detail.course?.id"/>
			</scroll-view>
		</view>
	</uni-popup>
	<uni-popup ref="ExamRef" type="bottom" borderRadius="10px 10px 10px 10px" backgroundColor="#fff">
		<view class="bgc-white">
			<scroll-view scroll-y style="max-height: 70vh">
				<view class="relative">
					<view class="text-32 text-center py-20">题目列表</view>
					<view class="time flex items-center" v-if="!isselect">
						<image class="timeicon mr-10" :src="`${$imageBaseUrl}course/time.png`"></image>
						{{formattedTime}}
					</view>
				</view>
				<c_exam :list="detail.questions" @submit="handleSubmit" :read="isselect" :useranswerlist="useranswerlist"/>
			</scroll-view>
		</view>
	</uni-popup>
</template>

<script setup>
import { getArticleDetail_api,getExerDetail_api, postStartExer_api, postSaveAnswer_api, postSubmitExer_api, getArticleWordsList_api } from '@/common/apis/course'
import { onLoad, onHide, onUnload } from "@dcloudio/uni-app"
import { computed, onMounted, reactive, ref, onBeforeUnmount } from 'vue'
import c_ranklist from './components/ranklist.vue'
import c_exam from './components/exam.vue'
import c_reac_text from './components/reac_text.vue'


const detail = ref({})
const articleRef = ref()
const isselect = ref(false)
let timer = null
const userId = ref(0);
const timeElapsed = ref(0)
const countup = () => {
    timeElapsed.value += 1
}

// 用户的答案列表，在练习详情接口来拿
const useranswerlist = ref([])
const isread = ref(false)
const wordlist= ref([])
onLoad(async o => {
	submitData.exerciseId = o.examId
	userId.value = o.userId || 0;
	if(o.read) {
		isselect.value = true
		let res = await getExerDetail_api({id: submitData.exerciseId})
		useranswerlist.value = res.log.answer
		// res.log.answer.forEach(item => {
			
		// })
	} 
	detail.value = await getArticleDetail_api({id: o.rankId, terminal: 'applet'})
	wordlist.value = await getArticleWordsList_api({articleId: detail.value.id})
	if(o.read){
		isread.value = true
	}
}) 

async function joinSucces(){
	wordlist.value = await getArticleWordsList_api({articleId: detail.value.id})
}

function handleRank(id){
	uni.redirectTo({
		url: `/pages/course/reading/info?rankId=${id}&examId=${submitData.exerciseId}`
	})
}

// onMounted(() => {
// 	const inneraudio = uni.createInnerAudioContext()
// })

const inneraudio = uni.createInnerAudioContext()

inneraudio.onEnded(() => {
	isplayStatus.value = false
})
inneraudio.onPlay(() => {
	isplayStatus.value = true
})
inneraudio.onStop(() => {
	isplayStatus.value = false
})
const isplayStatus = ref(false)
function playEvent(){
	if(!isplayStatus.value){
		inneraudio.autoplay = true
		inneraudio.src = detail.value.voiceFile.url
		inneraudio.play()
	} else{
		console.log('停止音乐')
		inneraudio.stop()
		isplayStatus.value = false
	}
}

onBeforeUnmount(() => {
	console.log('卸载了组件')
	inneraudio.stop()
	isplayStatus.value = false
	clearInterval(timer)
})
onHide(() => {
	console.log('隐藏了页面')
	inneraudio.stop()
	isplayStatus.value = false
	clearInterval(timer)
})

const ExamRef = ref()
async function handleStart(){
	if(!isselect.value){
		let res = await postStartExer_api({articleId: detail.value.id, exerciseId: submitData.exerciseId})
		submitData.logId = res.logId
	}
	ExamRef.value.open()
	if(!isread.value && !timer){
		timer = setInterval(countup, 1000)
	}
}

const popupRef = ref()
const isListShow = ref(false)
function selectListEvent(){
	popupRef.value.open('bottom')
}

function popupStatusEvent(data){
	isListShow.value = data.show
}

const submitData = reactive({
	logId: 0,
	exerciseId: 0,
	answers: []
})

const formattedTime = computed(() => {
    const minutes = Math.floor(timeElapsed.value / 60)
    const seconds = timeElapsed.value % 60
    return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
})

async function handleSubmit(data) {
	if(timeElapsed.value < 60){
		uni.showToast({
			icon: 'none',
			title: '60秒之内不能提交答案，请再检查检查吧'
		})
		return false
	}
    clearInterval(timer)
    submitData.answers = data
    await postSaveAnswer_api(submitData)
    await postSubmitExer_api({...submitData, ...{useTime: timeElapsed.value, userId: userId.value }});
	uni.redirectTo({
		url: `/pages/course/reading/result?examId=${submitData.exerciseId}`
	})
	// uni.$fui.href(`/pages/course/reading/result?examId=${submitData.exerciseId}`)
}

const reactextRef = ref()
const reactextStatus = ref(false)
function switchStatus(){
	reactextStatus.value = !reactextStatus.value
	reactextRef.value.changeStatus()
}

function goMark(){
	if (!wordlist.value?.length) {
		uni.showToast({ icon: 'none', title: '请先加入生词哦~' });
		return;
	};
	
	uni.navigateTo({
		url: `/pages/course/reading/mark?articleId=${detail.value.id}&userId=${userId.value}`
	})
}
</script>

<style lang="scss" scoped>
.bottombox{padding: 20rpx 32rpx;}
.btn{height: 80rpx; border-radius: 12rpx; flex: 1; text-align: center; line-height: 80rpx; color: #fff; font-size: 28rpx; display: flex; align-items: center; justify-content: center; position: relative;}
.btn+.btn{margin-left: 20rpx;}	

.time{position: absolute; right: 20rpx; top: 20rpx;}
.timeicon{width: 30rpx; height: 30rpx;}

.mp3icon{ display: flex; flex-flow: row nowrap; align-items: center; justify-content: space-between; width: 30rpx; margin-left: 20rpx;}
.mp3icon .item{width: 4rpx;height: 14rpx;background-color: #fff;}

.mp3icon .item:nth-of-type(1) {
  animation: grow 1s -0.45s ease-in-out infinite;
}

.mp3icon .item:nth-of-type(2) {
  animation: grow 1s -0.3s ease-in-out infinite;
}

.mp3icon .item:nth-of-type(3) {
  animation: grow 1s -0.15s ease-in-out infinite;
}

.mp3icon .item:nth-of-type(4) {
  animation: grow 1s ease-in-out infinite;
}

@keyframes grow {
  0%,
  100% {
    transform: scaleY(1);
  }

  50% {
    transform: scaleY(2);
  }
}
</style>